package com.py.credit.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.PromiseBookApprovalEnum;
import com.py.credit.service.PromiseBookApprovalService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/lyxx")
public class LyxxController {
	
	private final static String FRONT_TABLE_ID = "promiseBookApproval";

	@Autowired
	private PromiseBookApprovalService promiseBookApprovalService;

    @Autowired
    private RemoteBaseService remoteBaseService;
    
    @Value("${absolutepath}")
    private String absolutepath;
    
    private final static Map<String , String> tableFieldMap = new HashMap<String, String>();
    static {
    	tableFieldMap.put("t_zoo_subject_unique_100000" , "A000001-A000002");
    	tableFieldMap.put("t_zoo_subject_unique_100001" , "B000001-B000002");
    	tableFieldMap.put("t_zoo_subject_unique_100002" , "C000001-C000002");
    }
    
    /**
     * 校验审核状态，每次查询前，先校验所有关联状态（relation_status=‘0’（未关联）的记录），如果可以在相对应的库中（法人库，自然人库，非企业法人库）
     * 找到这些记录的主体名称或者统一社会信用代码，则把状态手动改为可关联（set relation_status = ‘3’）
     */
    private void checkRelationStatus() {
    	List<Map<String, Object>> wspDatas = promiseBookApprovalService.getWspDatas();
    	
    	for (Map<String, Object> map : wspDatas) {
			String ztName = (String)map.get("zt_name");
			String tyshxydm = (String)map.get("tyshxydm");
			String tableName = (String)map.get("tableName");
			Long id = (Long)map.get("id");
			if(StringUtils.isEmpty(ztName) || StringUtils.isEmpty(tyshxydm) || StringUtils.isEmpty(tableName) || id == null || id == 0L) {
				continue;
			}
			
			List<String> tybms = promiseBookApprovalService.selectTybmByZt(ztName,tyshxydm , tableName,tableFieldMap.get(tableName).split("-")[0],tableFieldMap.get(tableName).split("-")[1]);
			if(tybms.size() == 1) {
				if(!StringUtils.isEmpty(tybms.get(0))) {
					promiseBookApprovalService.renewPromiseBooks(tybms.get(0), id);
				}
			}
			
		}
    }


    
    /**
     * 查询本单位上报的所有未删除的承诺书 高级检索
     * @param type   承诺书类型:主动承诺和行业自律型承诺（ZD）、审批替代型承诺（SP）、容缺受理型承诺（RQ）、失信修复型承诺（SX）',
     * @param ztType 主体类型：'P'自然人,'C'企业法人,'F'非企业法人
     * @param bookStatus  承诺书上报状态：初始状态（0），待审核（1），审核通过（2），审核未通过（3）,
     * @param relationStatus  承诺书关联状态：未关联（0），已关联（1）
     * @param condition
     * @param page
     * @param request
     * @return
     */
    @IgnoreAuthority
    @RequestMapping(value = "/getPromiseBooks.json")
    public RestServiceResult<List<Map<String, Object>>> getPromiseBooks(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "lyzt",required = false,defaultValue = "") String lyzt,
    		@RequestParam(value = "relationStatus",required = false,defaultValue = "") String relationStatus,
    		@RequestParam(value = "sbtype", required = false, defaultValue = "") String sbtype,
    		@RequestParam(value = "condition", defaultValue = "", required = false) String condition ,
    		Page page , HttpServletRequest request) {
    	
    	new Thread(new Runnable() {
			@Override
			public void run() {
				checkRelationStatus();
			}
		}).start();
    	
    	
    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
       
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
        
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? PromiseBookApprovalEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        String[] additionalColumns = {};
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
        	if(rolename.equals("系统管理员")) {
        		list = promiseBookApprovalService.getPromiseBooksByConditionForPage(
                		type,ztType,lyzt,relationStatus,null,showColumns,additionalColumns, condition, page,sbtype,null);
			}else if(rolename.equals("部门管理员")) {
				list= promiseBookApprovalService.getPromiseBooksByConditionForPage(
		        		type,ztType,lyzt,relationStatus,userInfo.getOfficeId(),showColumns,additionalColumns, condition, page,sbtype,null);
			}else {
				 list = promiseBookApprovalService.getPromiseBooksByConditionForPage(
		        		type,ztType,lyzt,relationStatus,userInfo.getOfficeId(),showColumns,additionalColumns, condition, page,sbtype,userId);
			}
        	
        	
        	result.setData(list);
        	result.setCount(page.getTotalCount());
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;

    }
    
    
    /**
     * 审批上报承诺书，审批通过的，要去到相应的数据库去找主体信息（名称，统一社会信用代码），找到了，把关联状态（relation_status）改为已关联，找不到就是未关联
     * @param id     
     * @param bookStatus        审批过后的承诺书状态
     * @param approvalOpinion   审批意见
     * @param ztType			主体类型    ==  确定表名
     * @param ztName			主体名称    ==  条件
     * @param tyshxydm			统一社会信用代码   == 条件
     * @param request
     * @return
     */
    @RequestMapping(value = "/approvalPromiseBook.json")
    public RestServiceResult<Object> approvalPromiseBook(
    		@RequestParam(value = "ids",required = true,defaultValue = "") String ids,
    		@RequestParam(value = "approvalStatus",required = true,defaultValue = "") String approvalStatus,
    		@RequestParam(value = "approvalOpinion",required = true,defaultValue = "") String approvalOpinion,
    		HttpServletRequest request){
    	
    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo) {
	            ExceptionLogger.error("PromiseBookApprovalController#approvalPromiseBook", "未获取到当前用户信息！");
	            return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookApprovalController#approvalPromiseBook", "未获取到当前用户信息！");
            return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }
        
        Long userId = userInfo.getId();
        String userName = userInfo.getRealName();
        
        int updateCount = 0;
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        
        if(approvalOpinion.length() > 500) {
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("驳回意见最大500个字符！");
        	
        	return result;
        }
        
        boolean b = false;
        
        String[] idArr = ids.split(",");
        for(String idStr:idArr) {
        	Long id = Long.parseLong(idStr);
        	
        	Map<String, String> one = promiseBookApprovalService.selectOne(id);
        	String ztType = one.get("ztType");
        	String ztName = one.get("ztName");
        	String tyshxydm = one.get("tyshxydm");
        	String bookStatus = one.get("bookStatus");
        	
        	// 只有当前状态为1的，才能审批
        	if("1".equals(bookStatus)) {
        		
        		b = true;
        		
            	String fieldZtName = ""; 
                String fieldTyshbm = "";
                switch (ztType) {
        		case "100000":
        			fieldZtName = "A000001";
        			fieldTyshbm = "A000002";
        			break;
        		case "100001":
        			fieldZtName = "B000001";
        			fieldTyshbm = "B000002";
        			break;
        		case "100002":
        			fieldZtName = "C000001";
        			fieldTyshbm = "C000002";
        			break;
        		default:
        			break;
        		}
                
                int successCount = 0;
                try {
                	if("2".equals(approvalStatus)) {
                		String tableName = "t_zoo_subject_unique_"+ztType;
                		List<String> tybms = promiseBookApprovalService.selectTybm(tableName,fieldZtName,ztName,fieldTyshbm,tyshxydm);
                		if(tybms.size() != 1)  {
                			successCount = promiseBookApprovalService.approvalPromiseBook(userId,userName,id,approvalStatus,approvalOpinion,"","0");
                			if(successCount > 0) {
                				updateCount++;
                			}
                		}else {
                			successCount = promiseBookApprovalService.approvalPromiseBook(userId,userName,id,approvalStatus,approvalOpinion,tybms.get(0),"1");
                			if(successCount > 0) {
                				updateCount++;
                			}
                		}
                	}else {
                		successCount = promiseBookApprovalService.approvalPromiseBook(userId,userName,id,approvalStatus,approvalOpinion,"","0");
                		if(successCount > 0) {
            				updateCount++;
            			}
                	}
                }catch (Exception e) {
                	result.setCode(RestServiceResult.CODE_UNKNOW);
                	result.setMsg("审批异常，请联系管理员！");
                	
                	return result;
        		}
        	}
        }
        
        
        if(b) {
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	result.setMsg("审批成功" + updateCount + "条。");
        }else {
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("审核状态为审核通过和驳回，无法提交审核.");
        }
        
        return result;
    }
    
    
    
    /**
     * 预览和下载承诺书图片
     * @param id  这一行的id
     * @param previewOrDownload  预览或者下载参数  1：预览 2：下载
     * @param request
     * @return
     */
    @RequestMapping(value = "/promiseBookPreview.json")
    public void promiseBookPreview(
    		@RequestParam(value = "previewOrDownload", required = true,defaultValue = "") Integer param,
    		@RequestParam(value = "id", required = true,defaultValue = "") Long id,
    		HttpServletRequest request,HttpServletResponse response) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        String path = promiseBookApprovalService.promiseBookPreview(id);
        
        if(!new File(path).exists()) {
        	throw new ServiceException("文件不存在，或者已经被移除！");
        }
        
        
        if(param == 1) {
        	
        		response.setContentType("image/png");
        
        	
            response.setCharacterEncoding("UTF-8");
            try {
            	OutputStream outputSream = response.getOutputStream();

                InputStream fileInputStream = new FileInputStream(path);
                byte[] data = this.toByteArray(fileInputStream);
                fileInputStream.close();

                InputStream in = new ByteArrayInputStream(data);
                in.close();
                int len = 0;

                byte[] buf = new byte[1024];
                while ((len = in.read(buf, 0, 1024)) != -1) {
                    outputSream.write(buf, 0, len);
                }

                outputSream.close();
            }catch (Exception e) {
            	
            	throw new ServiceException("解析承诺书异常，请联系管理员！");
    		}
        }else {
        	FileUtils.downloadFile(path, response);
        }
        
    }
    
    
    private byte[] toByteArray(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
    
    //表头展示列
    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
        return new RestServiceResult<>(PromiseBookApprovalEnum.getOptionalColumns());
    }
    
    // 高级查询自定义列表选项
    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
        return new RestServiceResult<>(PromiseBookApprovalEnum.getAdvancedConditionColumns());
    }
    
    @RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("PromiseBookApprovalController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");
			
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}
    
    /**
     * 
     * @param type
     * @param ztType
     * @param bookStatus
     * @param relationStatus
     * @param condition
     * @param columnEN
     * @param page
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/export.json")
    public void export(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "bookStatus",required = false,defaultValue = "") String bookStatus,
    		@RequestParam(value = "relationStatus",required = false,defaultValue = "") String relationStatus,
    		@RequestParam(value = "sbtype", required = false, defaultValue = "") String sbtype,
    		@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            Page page,HttpServletResponse response,HttpServletRequest request) throws IOException {
    	
    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo) {
	            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
	            throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        if("undefined".equals(ztType)) {
        	ztType = "";
        }
        Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
        page.setLimit(1000);
        List<String> columns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> data ;
        if(rolename.equals("系统管理员")) {
        	data = promiseBookApprovalService.getPromiseBooksByConditionForPage(
            		type,ztType,bookStatus,relationStatus,null,columns,null, condition, page,sbtype,null);
		}else if(rolename.equals("部门管理员")) {
			data= promiseBookApprovalService.getPromiseBooksByConditionForPage(
	        		type,ztType,bookStatus,relationStatus,userInfo.getOfficeId(),columns,null, condition, page,sbtype,null);
		}else {
			data = promiseBookApprovalService.getPromiseBooksByConditionForPage(
	        		type,ztType,bookStatus,relationStatus,userInfo.getOfficeId(),columns,null, condition, page,sbtype,userId);
		}
        List<OptionalColumn> optionalColumns = PromiseBookApprovalEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, data, "承诺书记录", "承诺书记录", columns, optionalColumns);
    }
    
    

    
}
